package com.extweb4j.core.kit;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.extweb4j.core.enums.RowStatus;
import com.extweb4j.core.model.ExtUser;
import com.jfinal.kit.PropKit;
/**
 * 登录工具类
 * @author Administrator
 *
 */
public class LoginKit {
	/**
	 * 登录
	 * @param request
	 * @return
	 */
	public static String login(HttpServletRequest request){
		
		String userId  = request.getParameter("userid");
		String password  = request.getParameter("password");
		String captcha = request.getParameter("captcha");
		
		if(StringUtils.isBlank(userId) || StringUtils.isBlank(password)){
			
			throw new RuntimeException("用户名,密码不能为空");
		}
		
		boolean useCaptcha = PropKit.getBoolean("useCaptcha",true);
		
		if(useCaptcha){
			
			if(StringUtils.isBlank(captcha)){
				throw new RuntimeException("验证码不能为空");
			}
			
			String captchaMd5 =  captcha.toLowerCase();
			Object sessionCaptchaMd5 = request.getSession().getAttribute("captcha");
			
			if(sessionCaptchaMd5 == null){
				throw new RuntimeException("验证码已过期,请刷新重试");
			}
			if(!captchaMd5.equals(sessionCaptchaMd5.toString().toLowerCase())){
				throw new RuntimeException("验证码输入错误");
			}
		}
		
		ExtUser user = ExtUser.dao.findUserBy(userId,ExtKit.MD5(password));
		
		if(user == null){
			
			throw new RuntimeException("用户名或密码错误");
			
		}else{
			String userStatus = user.getStr("row_status");
			
			if(userStatus == null){
				
				throw new RuntimeException("您的账号状态异常,暂时无法使用,请联系超级管理员");
				
			}else if(userStatus .equals( RowStatus.启用.getState() )){
				
				String uid =   user.getId();
				request.getSession().setAttribute("uid",uid);
				return uid;
			}
			
			throw new RuntimeException("您的账号已被锁定,请联系超级管理员");
			
		}
		
	}
	/**
	 * 验证是否登录
	 * @param request
	 * @return
	 */
	public static boolean isLogin(HttpServletRequest request){
		
		if(request.getSession().getAttribute("uid") != null){
			return true;
		}
		return false;
	}
	/**
	 * 退出
	 * @param request
	 * @return
	 */
	public static boolean logout(HttpServletRequest request){
		
		request.getSession().invalidate();
		
		return true;
	}
	
	/**
	 * 验证是否登录
	 * @param request
	 * @return
	 */
	public static ExtUser getSessionUser(HttpServletRequest request){
		
		Object uid = request.getSession().getAttribute("uid");
		
		if(uid == null){
			throw new RuntimeException("您的登录已过期,请重新登录");
		}
		
		ExtUser user = ExtUser.dao.findById(uid);
		
		return user;
	}
	
}
